import ListEmpty from '@/components/antd-comp/empty'
import ModalComponent from '@/components/antd-comp/modal/ModalComponent'
import TabsDropComponent from '@/components/antd-comp/tabs'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import { Accordion } from '@/components/bs-ui/accordion'
import { getPublished_list } from '@/controllers/API/assistant'
import { filterPublishToolNames } from '@/pages/SkillPage/constants'
import { Func } from '@/permissions/constants'
import { useDictStore } from '@/store/dictStore'
import { useFuncsStore } from '@/store/funcStore'
import { usePluginStore } from '@/store/pluginStore'
import { useRouteStoreHook } from '@/store/routeStore'
import { Input } from 'antd'
import { useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router-dom'
import ToolItem from '../../SkillPage/components/ToolItem'
import '../../SkillPage/css/tabTools.less'
import '../css/pluginDia.less'

const PluginDia = ({ open, setOpen, select = null, onSelect }) => {
  /* 取消 */
  const handleCancel = (e: React.MouseEvent<HTMLElement>) => {
    setOpen(false)
  }
  /**
   * 功能权限限制
   */
  const { hasFuncPermission } = useFuncsStore()
  const navigate = useNavigate()
  const [keyword, setKeyword] = useState(' ')
  const [allData, setAllData] = useState([])
  const { t } = useTranslation()

  /**
   * 涉及顶部路由信息，在对应页面进行处理
   */
  const routeNames = [t('menu.plugin')]
  useRouteStoreHook(routeNames)
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-expect-error
  const { setPluginDetail } = usePluginStore()

  const [type, setType] = useState('') // '' add edit
  /* Spin 参数 */
  const [dataLoading, setDataLoading] = useState(true)

  // select type
  const [typeList, setTypeList] = useState([])
  const [selected, setSelected] = useState('')

  const { loadDictOptions } = useDictStore()
  const initData = (type = 'category') => {
    loadDictOptions(type).then(res => {
      res.unshift({
        value: '',
        label: '全部类型',
        id: 0
      })
      setTypeList(res)
    })
  }

  const loadData = async (is_preset, is_custom, categoryCode: string) => {
    if (!hasFuncPermission([Func.tools.query])) return
    try {
      setDataLoading(true)
      setAllData([])
      const res = await getPublished_list(is_preset, is_custom, categoryCode, true)
      const list = res.list || []

      const processedList = list.map(item => ({
        ...item,
        children: item.children.map(childItem => ({
          ...childItem,
          tool_id: item.tool_id
        }))
      }))

      const filteredList = is_preset
        ? processedList.filter(item => filterPublishToolNames.includes(item.name))
        : processedList

      setAllData(filteredList)
      setKeyword('')
    } catch (err) {
      console.error('Error fetching published list:', err)
    } finally {
      setDataLoading(false)
    }
  }

  const handeleTypeSelected = item => {
    setSelected(item.value)
    loadData(type === '', false, item.value)
  }

  useEffect(() => {
    loadData(type === '', false, '')
    initData()
  }, [type])

  const options = useMemo(() => {
    return (
      allData?.filter(
        el =>
          el.name.toLowerCase().includes(keyword.toLowerCase()) ||
          el.description.toLowerCase().includes(keyword.toLowerCase())
      ) || []
    )
  }, [keyword, selected, allData])

  const handleEdit = (event, el) => {
    event.stopPropagation()
    setPluginDetail(el)
    navigate(`/plugin/create/${el.id}`)
  }

  return (
    <>
      <ModalComponent
        title={'添加插件'}
        width={1200}
        className="pluginDia_DiaCont Application_DiaCont max-h-[50%]"
        style={{ top: '10%' }}
        open={open}
        footer={[]}
        content={
          <div className="caseOverFlowY relative" style={{ background: '#fff', height: '70vh' }}>
            <div className="relative flex h-full w-full overflow-y-scroll rounded-[6px] bg-[#fff] scrollbar-hide">
              <div
                className="plugin-border-right w-[25%] min-w-[200px] max-w-[400px]"
                style={{ padding: '0 1.5rem 1.5rem 0' }}
              >
                <Input
                  size="large"
                  placeholder={t('tools.search')}
                  prefix={
                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <circle
                        cx="6.96436"
                        cy="6.96484"
                        r="5"
                        stroke="black"
                        strokeWidth="1.5"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                      <path
                        d="M10.5 10.5L14.0355 14.0355"
                        stroke="black"
                        strokeWidth="1.5"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                    </svg>
                  }
                  className="mt-6"
                  onChange={e => {
                    setKeyword(e.target.value)
                  }}
                />
                <ThemeBtn
                  className="mt-4  w-full"
                  style={{ height: '36px', borderRadius: '8px' }}
                  onClick={() => {
                    if (!hasFuncPermission([Func.tools.add])) {
                      return
                    }
                    // navigate('/plugin/create/0')
                    window.open('/plugin/create/0')
                  }}
                  shape="pill"
                >
                  {t('create')}
                  {t('tools.createCustomTool')}
                </ThemeBtn>
                <div className="mt-4">
                  <div
                    className={`hover:bg-plugin' flex cursor-pointer items-center gap-2 rounded-md px-4 py-2 transition-all duration-200 ${
                      type === '' && 'bg-[#E0E7FF]'
                    }`}
                    style={{ height: '36px' }}
                    onClick={() => {
                      setType('')
                    }}
                  >
                    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path
                        d="M8 16H3V4H14V7"
                        stroke="#232E3E"
                        strokeWidth="1.5"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                      <path
                        d="M12 16H14.5C15.8807 16 17 14.8807 17 13.5V13.5C17 12.1193 15.8807 11 14.5 11H8"
                        stroke="#232E3E"
                        strokeWidth="1.5"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                      <path
                        d="M10 9L8 11L10 13"
                        stroke="#232E3E"
                        strokeWidth="1.5"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                    </svg>
                    <span style={{ fontSize: '14px', fontWeight: 400 }}>{t('tools.builtinTools')}</span>
                  </div>
                  <div
                    className={`hover:bg-plugin' mt-4 flex cursor-pointer items-center gap-2 rounded-md px-4 py-2 transition-all duration-200 ${
                      type === 'edit' && 'bg-[#E0E7FF]'
                    }`}
                    style={{ height: '36px' }}
                    onClick={() => {
                      setType('edit')
                    }}
                  >
                    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path
                        d="M9.10628 2.56826C9.45106 1.81058 10.5489 1.81058 10.8937 2.56826L12.4734 6.03968C12.6156 6.35217 12.9171 6.56673 13.2644 6.60264L17.123 7.00156C17.9651 7.08863 18.3044 8.11144 17.6753 8.66678L14.7931 11.2112C14.5336 11.4402 14.4184 11.7874 14.4909 12.122L15.296 15.84C15.4717 16.6515 14.5835 17.2836 13.8499 16.8692L10.4889 14.9703C10.1863 14.7993 9.81368 14.7993 9.51112 14.9703L6.15012 16.8692C5.41654 17.2836 4.52834 16.6515 4.70405 15.84L5.50909 12.122C5.58156 11.7874 5.46641 11.4402 5.20695 11.2112L2.32469 8.66677C1.69561 8.11144 2.03487 7.08863 2.87704 7.00156L6.73559 6.60264C7.08294 6.56673 7.3844 6.35217 7.52661 6.03968L9.10628 2.56826Z"
                        fill="black"
                      />
                    </svg>
                    <span style={{ fontSize: '14px', fontWeight: 400 }}>{t('tools.customTools')}</span>
                  </div>
                </div>
              </div>
              {/* cont */}
              <div
                className={
                  type == 'edit' && typeList.length
                    ? 'paddtop_tabtools h-full flex-1 overflow-auto bg-[#fff]  scrollbar-hide'
                    : 'paddtopDef_tabtools h-full flex-1 overflow-auto bg-[#fff]  scrollbar-hide'
                }
                style={{ position: 'relative', padding: '0 0 1.5rem 0' }}
              >
                {/* 筛选 */}
                <div className="select-type absolute top-[0px] z-[49] bg-[#fff]">
                  {type == 'edit' && typeList.length ? (
                    <TabsDropComponent
                      className="tab-tools-tabs"
                      list={typeList}
                      value={selected}
                      tabsDropFun={handeleTypeSelected}
                    ></TabsDropComponent>
                  ) : null}
                </div>
                {/* 内容 */}
                {dataLoading ? (
                  <div className="absolute left-0 top-0 z-10 flex h-full w-full items-center justify-center bg-[rgba(255,255,255,0.6)] dark:bg-blur-shared">
                    <span className="loading loading-infinity loading-lg"></span>
                  </div>
                ) : (
                  <Accordion type="single" collapsible className="h-full w-full overflow-auto scrollbar-hide">
                    {options.length ? (
                      options.map(el => (
                        <ToolItem
                          key={el.id}
                          // type={type}
                          type={''}
                          select={select}
                          data={el}
                          onSelect={onSelect}
                          onEdit={e => handleEdit(e, el)}
                          // onRecords={e => onRecords(e, el)}
                          onRecords={e => {}}
                        ></ToolItem>
                      ))
                    ) : (
                      <ListEmpty />
                    )}
                  </Accordion>
                )}
              </div>
            </div>
          </div>
        }
        onCancel={e => {
          handleCancel(e)
        }}
        onOk={() => {}}
      />
    </>
  )
}

export default PluginDia
